package com.bw.lib_storage.db

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import net.sqlcipher.database.SupportFactory

object DBUtils {

    private lateinit var db:AppDataBase

    /**
     * 初始化数据库
     */
    fun init(context:Context,dbName:String){
        //版本升级1_2:新增字段
        val MIGRATION_1_2 = object :Migration(1,2){
            override fun migrate(db: SupportSQLiteDatabase) {
                db.execSQL("ALTER TABLE history ADD COLUMN query_time INTEGER NOT NULL DEFAULT 0")
            }
        }
        
        //版本升级2_3:重构播放历史表
        val MIGRATION_2_3 = object :Migration(2,3){
            override fun migrate(db: SupportSQLiteDatabase) {
                // 创建新的历史表
                db.execSQL("""
                    CREATE TABLE IF NOT EXISTS history_new (
                        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                        video_id TEXT NOT NULL,
                        title TEXT NOT NULL,
                        content TEXT NOT NULL DEFAULT '',
                        cover_url TEXT NOT NULL DEFAULT '',
                        video_url TEXT NOT NULL DEFAULT '',
                        duration INTEGER NOT NULL DEFAULT 0,
                        current_position INTEGER NOT NULL DEFAULT 0,
                        progress_percentage REAL NOT NULL DEFAULT 0.0,
                        last_play_time INTEGER NOT NULL,
                        query_time INTEGER NOT NULL,
                        user_id TEXT NOT NULL DEFAULT '',
                        author_name TEXT NOT NULL DEFAULT '',
                        play_count INTEGER NOT NULL DEFAULT 1,
                        is_completed INTEGER NOT NULL DEFAULT 0
                    )
                """)
                
                // 迁移旧数据
                db.execSQL("""
                    INSERT INTO history_new (id, title, content, query_time, video_id, last_play_time)
                    SELECT id, title, content, query_time, id, query_time FROM history
                """)
                
                // 删除旧表
                db.execSQL("DROP TABLE history")
                
                // 重命名新表
                db.execSQL("ALTER TABLE history_new RENAME TO history")
            }
        }
        
        db = Room.databaseBuilder(context,AppDataBase::class.java,dbName)
            .allowMainThreadQueries() //不规范的，协程线程访问数据库，耗时操作
            .openHelperFactory(SupportFactory("123456".toByteArray())) //数据库加密
            .addMigrations(MIGRATION_1_2, MIGRATION_2_3) //添加升级1-2和2-3
            .build()
    }

    /**
     * 获得数据库
     */
    fun getDB():AppDataBase{
        if (db == null){
            throw NullPointerException("请先初始化数据库")
        }
        return db
    }


}